import csv
import json
import re
import numpy as np
import glob

parsed_objects = []
count=0
sub_string_pattern = r"\d{1,2}[A-Z]{3}\d{4}\s\d{2}:\d{2}:\d{2}\.\d{3}"

def count_csv_rows(file_path):
    with open(file_path, newline='') as csvfile:
        csv_reader = csv.reader(csvfile)
        row_count = sum(1 for row in csv_reader)
    return row_count

def append_to_csv(file_path, data, flag):
    # if len(data) > 50  and len(data) < 70:
        with open(file_path, 'a', newline='') as csvfile:  # 以附加模式打开文件
            csv_writer = csv.writer(csvfile)
            row = [flag] + data
            csv_writer.writerow(row)

files = 'data/normal sapirate in saha/normal ASPirate in SAHA （取消1mm抬升-13#/*/*.csv'

csv_files = glob.glob(files)

# line_indices = [1,4,7,10,13]
for path in csv_files:
    # 打开 CSV 文件
    line_indices = list(range(1, count_csv_rows(path)+1, 1))
    # line_indices = [0]
    with open(path, newline='') as csvfile:
        # 创建一个 CSV 读取器对象
        count = 0
        success = 0
        csv_reader = csv.reader(csvfile)
        # 逐行读取 CSV 文件内容并打印出来
        for i, row in enumerate(csv_reader):
            if i in line_indices:
                result = ",".join(row)
                match = re.search(sub_string_pattern, result)
                try:
                    start_index = match.start()
                    end_index = match.end()
                except AttributeError:
                    print(path)
                    break
                modified_result = result[:start_index-1] + '0' + result[end_index+1:]
                fixed_json_str = re.sub(r'(?<!["\w])(\w+)(?=:)', r'"\1"', modified_result)
                jdata = json.loads(fixed_json_str)
                parsed_objects = jdata["Pressure_readings"]
                # print(parsed_objects)
                index = [point for point, value in enumerate(parsed_objects) if value > 3000]
                # print(index)
                try:
                    sub_list = parsed_objects[index[2]+1:index[3]]
                except IndexError:
                    count+=1
                try:
                    success += 1
                    append_to_csv('data/Output.csv', sub_list, 0)
                    # append_to_csv('data/test.csv', sub_list, 0)
                except NameError:
                    continue
print("ERROR:",count)
print("SUCCESS:",success)